package com.demo.gulimall.product.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.demo.common.utils.ExportToExcelUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lxf
 * @description
 * @date 2021/3/4 20:08
 */
@RequestMapping("/excelAction")
@RestController
public class ExportController {
    Log log = LogFactory.get(ExportController.class);

    @RequestMapping("/exportToExcel")
    public Object exportToExcel(HttpServletResponse response) {
        //数据源
        List<ExcelPropertyIndexModel> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            ExcelPropertyIndexModel model = new ExcelPropertyIndexModel();
            model.setName("热巴" + i);
            model.setAge(i + 1);
            model.setAddress("北京" + i);
            model.setEmail(RandomUtil.randomNumbers(7) + "@qq.com");
            log.info("mode:{}", model.toString());
            list.add(model);
        }
        String sheetName = "信息表";
        String fileName = "导出表";
        ExcelTypeEnum excelType = ExcelTypeEnum.XLSX;

        OutputStream outputStream = null;
        try {
            outputStream = ExportToExcelUtils.getOutputStream(fileName, response, ExcelTypeEnum.XLSX);
            if (list.size() > ExportToExcelUtils.MAX_ROW) {
                ExportToExcelUtils.exportMore(outputStream, ExcelPropertyIndexModel.class, excelType, list);
            } else {
                ExportToExcelUtils.export(outputStream, ExcelPropertyIndexModel.class, sheetName, excelType, list);
            }
            log.info("写入成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出信息失败！{}", e.getMessage());
        }
        return null;
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ExcelPropertyIndexModel extends BaseRowModel {

    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "年龄", index = 1)
    private Integer age;

    @ExcelProperty(value = "邮箱", index = 2)
    private String email;

    @ExcelProperty(value = "地址", index = 3)
    private String address;

}